Preact is a front end web framework that’s similar to React.
It’s smaller and less complex than React.
In this article, we’ll look at how to get started with front end development with Preact.
Shallow Rendering
We can shallow render one level of a component only with shallow rendering.
For example, we can write:
import { shallowRender } from "preact-render-to-string";
import { h } from "preact";
const Foo = () => <div>foo</div>;
const App = (
<div class="foo">
<Foo />
</div>
);
console.log(shallowRender(App));
to render the App
component without rendering the Foo
component.
Then when we log the returned string, we get:
'<div class="foo"><Foo></Foo></div>'
logged.
Pretty Mode
We can render the string in a more human-friendly way with the pretty
option.
To use it, we write:
import { render } from "preact-render-to-string";
import { h } from "preact";
const Foo = () => <div>foo</div>;
const App = (
<div class="foo">
<Foo />
</div>
);
console.log(render(App, {}, { pretty: true }));
Then we see:
<div class="foo">
<div>foo</div>
</div>
logged.
JSX Mode
The JSX rendering mode is useful if we’re doing any kind of snapshot testing.
It renders the output as if it’s written with JSX.
For example, we can write:
import render from "preact-render-to-string/jsx";
import { h } from "preact";
const App = <div data-foo={true} />;
console.log(render(App));
Then we see:
<div data-foo={true}></div>
logged.
External DOM Mutations
We can add external DOM mutation code in our component.
To do this, we have to disable the virtual DOM rendering and diffing algorithm so that it won’t undo any external DOM manipulations in a component.
For example, we can write:
import { Component, render } from "preact";
class Example extends Component {
shouldComponentUpdate() {
return false;
}
componentDidMount() {
let thing = document.createElement("maybe-a-custom-element");
this.base.appendChild(thing);
}
componentWillUnmount() {}
render() {
return <div class="example" />;
}
}
const App = () => <Example />;
if (typeof window !== "undefined") {
render(<App />, document.getElementById("root"));
}
We return false
in shouldComponentUpdate
to disable the virtual DOM diffing algorithm.
Then in componentDidMount
, we call document.createElement
to add a new element into the DOM.
Conclusion
We can shallow render and pretty print components rendered in a string.
Also, we can manipulate the DOM directly in our Preact components.